import { XFlowGraphCommands, XFlowNodeCommands, IconStore, MODELS, createToolbarConfig } from '@antv/xflow'
import { SaveOutlined, PlusCircleOutlined, DeleteOutlined } from '@ant-design/icons'
import { message } from 'antd'
import type { NsGraphCmd, NsNodeCmd, IModelService, IToolbarItemOptions, NsGraph } from '@antv/xflow'
import { renderCanvas } from './comannd-utils'
import { APP } from './index'
import { removeNode,saveChartflowData,getChartflowData } from '@net/dataview/index'

/** toolbar依赖的状态 */
export interface IState {
  isNodeSelected: boolean,
  nodes: NsGraph.INodeConfig[]
}

namespace NsConfig {
  /** 注册icon 类型 */
  IconStore.set('PlusCircleOutlined', PlusCircleOutlined)
  IconStore.set('DeleteOutlined', DeleteOutlined)
  IconStore.set('SaveOutlined', SaveOutlined)
  /** nodeId */
  let id = 1

  /** 获取toolbar依赖的状态 */
  export const getToolbarState = async (modelService: IModelService) => {
    // nodes
    const nodes = await MODELS.SELECTED_NODES.useValue(modelService)
    return {
      isNodeSelected: nodes.length > 0,
      nodes: nodes
    } as IState
  }


  /** 获取toobar配置项 */
  export const getToolbarItems = async (state: IState) => {
    const toolbarGroup1: IToolbarItemOptions[] = []
    const toolbarGroup2: IToolbarItemOptions[] = []
    /**添加节点 */
    toolbarGroup1.push({
      id: XFlowNodeCommands.ADD_NODE.id,
      iconName: 'PlusCircleOutlined',
      tooltip: '添加节点',
      onClick: async ({ commandService }) => {
        const nodeName = `Node-${id}`
        commandService.executeCommand<NsNodeCmd.AddNode.IArgs>(XFlowNodeCommands.ADD_NODE.id, {
          nodeConfig: {
            id: nodeName,
            label: nodeName,
            x: 100 + id * 5,
            y: 50 + id * 5,
            width: 160,
            height: 32,
            ports: {
              groups: {
                // 输入链接桩群组定义
                left: {
                  position: 'left',
                  attrs: {
                    circle: {
                      r: 6,
                      magnet: true,
                      stroke: '#31d0c6',
                      strokeWidth: 2,
                      fill: '#fff',
                    },
                  },
                },
                // 输出链接桩群组定义
                right: {
                  position: 'right',
                  attrs: {
                    circle: {
                      r: 6,
                      magnet: true,
                      stroke: '#31d0c6',
                      strokeWidth: 2,
                      fill: '#fff',
                    },
                  },
                },
                top: {
                  position: 'top',
                  attrs: {
                    circle: {
                      r: 6,
                      magnet: true,
                      stroke: '#31d0c6',
                      strokeWidth: 2,
                      fill: '#fff',
                    },
                  },
                },
                bottom: {
                  position: 'bottom',
                  attrs: {
                    circle: {
                      r: 6,
                      magnet: true,
                      stroke: '#31d0c6',
                      strokeWidth: 2,
                      fill: '#fff',
                    },
                  },
                },
              },
              items: [
                {
                  id: 'port1',
                  group: 'top',
                },
                {
                  id: 'port2',
                  group: 'right',
                },
                // {
                //   id: 'port3',
                //   group: 'in',
                // },
                {
                  id: 'port4',
                  group: 'bottom',
                },
                {
                  id: 'port5',
                  group: 'left',
                },
              ],
            }
          },
        })
        id += 1
      },
    })
    // 删除节点
    toolbarGroup1.push({
      id: XFlowNodeCommands.MOVE_NODE.id,
      iconName: 'DeleteOutlined',
      tooltip: '删除节点',
      isEnabled: state.isNodeSelected,
      onClick: async ({ commandService }) => {
        console.log(state?.nodes)
        const res = await removeNode({Id:state?.nodes[0]?.store?.data?.id});
        if (res.data.status === 200) {
          commandService.executeCommand<NsNodeCmd.DelNode.IArgs>(XFlowNodeCommands.DEL_NODE.id, {
            nodeConfig: state.nodes[0],
          })
        } else {
          message.error("删除失败，请重新操作！")
        }
      },
    })

    /** 保存数据 */
    toolbarGroup2.push({
      id: XFlowGraphCommands.SAVE_GRAPH_DATA.id,
      iconName: 'SaveOutlined',
      tooltip: '保存数据',
      onClick: async ({ commandService }) => {
        commandService.executeCommand<NsGraphCmd.SaveGraphData.IArgs>(
          XFlowGraphCommands.SAVE_GRAPH_DATA.id,
          {
            saveGraphDataService: async (meta, data) => {
              console.log(data)
              // saveFlowChartData(data);
              const res:any = await saveChartflowData(data);
              // console.log('res====',res);
              console.log("cavasRender===", res);
              if(res.data.status === 200){
                message.success("保存成功");
                const resD = await getChartflowData();
                resD.data.nodes.forEach((item: any) => {
                  item.id = item.fcId
                  item.ports = {
                    groups: {
                      // 输入链接桩群组定义
                      left: {
                        position: 'left',
                        attrs: {
                          circle: {
                            r: 6,
                            magnet: true,
                            stroke: '#31d0c6',
                            strokeWidth: 2,
                            fill: '#fff',
                          },
                        },
                      },
                      // 输出链接桩群组定义
                      right: {
                        position: 'right',
                        attrs: {
                          circle: {
                            r: 6,
                            magnet: true,
                            stroke: '#31d0c6',
                            strokeWidth: 2,
                            fill: '#fff',
                          },
                        },
                      },
                      top: {
                        position: 'top',
                        attrs: {
                          circle: {
                            r: 6,
                            magnet: true,
                            stroke: '#31d0c6',
                            strokeWidth: 2,
                            fill: '#fff',
                          },
                        },
                      },
                      bottom: {
                        position: 'bottom',
                        attrs: {
                          circle: {
                            r: 6,
                            magnet: true,
                            stroke: '#31d0c6',
                            strokeWidth: 2,
                            fill: '#fff',
                          },
                        },
                      },
                    },
                    items: [
                      {
                        id: 'port1',
                        group: 'top',
                      },
                      {
                        id: 'port2',
                        group: 'right',
                      },
                      // {
                      //   id: 'port3',
                      //   group: 'in',
                      // },
                      {
                        id: 'port4',
                        group: 'bottom',
                      },
                      {
                        id: 'port5',
                        group: 'left',
                      },
                    ],
                  }
                })
                resD.data.edges.forEach((item: any) => {
                  item.id = item.fcId
                })
                renderCanvas(APP, resD.data);
              }else{
                message.error("保存失败")
              }
            },
          },
        )
      },
    })

    return [
      { name: 'nodeGroup', items: toolbarGroup1 },
      { name: 'graphGroup', items: toolbarGroup2 },
    ]
  }
}

/** wrap出一个hook */
export const useToolbarConfig = createToolbarConfig(toolbarConfig => {
  /** 生产 toolbar item */
  toolbarConfig.setToolbarModelService(async (toolbarModel, modelService) => {
    // const toolbarItems = await NsConfig.getToolbarItems()
    // toolbarModel.setValue(toolbar => {
    //   toolbar.mainGroups = toolbarItems
    // })
    // 更新toolbar model
    const updateToolbarState = async () => {
      const toolbarState = await NsConfig.getToolbarState(modelService)
      const toolbarItems = await NsConfig.getToolbarItems(toolbarState)
      toolbarModel.setValue(toolbar => {
        toolbar.mainGroups = toolbarItems
      })
    }

    // 监听对应的model
    const model = await MODELS.SELECTED_NODES.getModel(modelService)
    model.watch(() => {
      updateToolbarState()
    })
  })
})